package com.ht.sps.util;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 薄成文 13-10-16 下午2:28
 * To change this template use File | Settings | File Templates.
 */
public class ValidationUtil {
    private static final Logger log = LoggerFactory.getLogger(ValidationUtil.class);
    private static Validator validator;
    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public static boolean isValidate(Object obj) {
        if (obj == null) {
            return false;
        } else {
            Set<ConstraintViolation<Object>> violationSets = validator.validate(obj);
            if (!violationSets.isEmpty()){
                log.error("========== Validate "+obj.getClass().getName()+" Begin ============");
                Iterator<ConstraintViolation<Object>> it  = violationSets.iterator();
                while (it.hasNext()) {
                    ConstraintViolation<Object> cv = it.next();
                    log.error(cv.getPropertyPath() + " ["+cv.getInvalidValue()+"] " +cv.getMessage());
                }
                log.error("========== Validate "+obj.getClass().getName()+" End ============");
            } else {
                log.debug(" Validate "+obj.getClass().getName()+" is OK! ============");
            }
            return violationSets.isEmpty();
        }
    }

    /**
     *判断字符串是否为"","null",null对象.如果是以上值,返回true
     * @param str
     * @return boolean
     */
    public static boolean isStringNull(String str){
        boolean rs = true;
        if("".equals(str) || "null".equals(str) || null==str){
            rs = true;
        }else{
            rs = false;
        }
        return rs;
    }

    /**
     * 校验是否是数据,不包括小数
     * 是数字返回true
     * @param str
     * @return
     */
    public static boolean isNumber(String str){
        java.util.regex.Pattern pattern=java.util.regex.Pattern.compile("[0-9]*");
        java.util.regex.Matcher match=pattern.matcher(str);
        if(match.matches()==false){
            return false;
        } else{
            return true;
        }
    }
}
